import 'dart:async';
import 'dart:math';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

class QkdAudioRecorder {
  static const MethodChannel _channel =
      const MethodChannel('qkd_audio_recorder');

  ValueChanged<double> _onRecorderDbChanged;

  ValueChanged<String> _onRecordComplete;

  ValueChanged<Map> _onUploadComplete;

  ValueChanged<String> _onRecordStarted;

  static const String TAG = "QkdAudioRecorder";

  bool isRecording=false;

  bool logEnabled = false;

  QkdAudioRecorder({
    ValueChanged<String> onRecordStarted,
    ValueChanged<String> onRecordComplete,
    ValueChanged<double> onRecorderDbChanged,
    ValueChanged<Map> onUploadComplete,
    this.logEnabled = false
  }){
    this._onRecorderDbChanged=onRecorderDbChanged;
    this._onRecordComplete=onRecordComplete;
    this._onUploadComplete = onUploadComplete;
    this._onRecordStarted = onRecordStarted;
    _channel.setMethodCallHandler(channelHandler);
  }

  startRecord() {
    if(logEnabled)print("$TAG message: start...");
    isRecording=true;
    _channel.invokeMethod("start").then((value){
      if(null != _onRecordStarted){
        _onRecordStarted(value);
      }
    });
  }

  stopRecord(){
    if(logEnabled)print("$TAG message: stop");
    isRecording=false;
    _channel.invokeMethod("stop").then((value){

    });
  }

  Future<String> channelHandler(MethodCall call){

    switch(call.method){
      case "onRecordSound":
        if(_onRecorderDbChanged!=null && call.arguments is int){
          if (Platform.isIOS){
            //0~40
            int voiceDb=max(0, min(40, call.arguments-95));
            if(_onRecorderDbChanged!=null){
              _onRecorderDbChanged(voiceDb/40.toDouble());
            }
          }else if (Platform.isAndroid){
            //0~40
            int voiceDb=max(0, min(40, call.arguments-50));
            if(_onRecorderDbChanged!=null){
              _onRecorderDbChanged(voiceDb/40.toDouble());
            }
          }
        }
        break;
      case "onRecordComplete":
        if(logEnabled)print("$TAG channelHandler: ${call.method} -- args: ${call.arguments}");
        if(_onRecordComplete!=null && call.arguments is String){
          _onRecordComplete(call.arguments);
        }
        break;
      case "onUploadComplete":
        if(logEnabled)print("$TAG channelHandler: ${call.method} -- args: ${call.arguments}");
        if(_onUploadComplete!=null){
          Map paramters = Map();
          if(Platform.isAndroid){
            paramters["url"] = call.arguments;
            paramters["code"] = 1;
          }else{
            paramters = call.arguments;

          }
          _onUploadComplete(paramters);
        }
        break;
    }
  }

  /// 停止
  static void destory() async {
    print("$TAG message: destory");
    _channel.invokeMethod('destory');
  }

}
